import { Component, OnInit, ViewChild, Inject, forwardRef, ChangeDetectorRef, EventEmitter, Output } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { FileUploader } from '../../../../../../lib/ng2-file-upload';
import { path } from '../../../../../path.config';
import { masterService } from '../../../../../../lib/master.service';
import { saveVarService } from '../../../../../../lib/saveVar.service';
import { AppComponent } from '../../../../../app.component';

import * as $ from 'jquery';

import { SelectImageEditComponent } from './select-image-edit/select-image-edit.component';
@Component({
    selector: 'app-three-advertising-edit',
    templateUrl: './three-advertising-edit.component.html',
    styleUrls: ['./three-advertising-edit.component.css'],
    providers: [saveVarService, forwardRef(() => AppComponent)]
})
export class ThreeAdvertisingEditComponent implements OnInit {
    @Output() editAdvertise: EventEmitter<any> = new EventEmitter()

    @ViewChild('editThreeAd') public editThreeAd: ModalDirective;
    @ViewChild('selectImageEdit') public selectImageGridModal: SelectImageEditComponent;
    // 列表项编辑提交
    private editListItem: any = path.advertising.threeAdvertising.editListItem;

    private addImgItem = path.imagesUpload.apiUrl;

    private getImgId = path.imagesUpload.getImgId;

    public options: Array<any> = [];
    public edit: any = {
        type: '',
        adName: '',
        imageId: '',
        url: '',
    }

    public uploadPic = {};

    constructor(private _masterService: masterService,
        public _saveVar: saveVarService,
        public cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    ngOnInit() { }

    public uploader: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 保存编辑已有列表项
    public EditListItem() {
        if (this._saveVar.threeAdEditPicId) {
            this.edit.imageId = this._saveVar.threeAdEditPicId;
        }

        if (!this.edit.adName) {
            this.app.toastWarning('请填写名称！');
            return;
        } else if (!this.edit.imageId) {
            this.app.toastWarning('请上传图片！');
            return;
        } else if (!this.edit.type) {
            this.app.toastWarning('请选择位置！');
            return;
        }
        this._masterService
            .postData(this.editListItem, this.edit)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.app.toastSuccess('保存成功！');
                    this.editThreeAd.hide();
                    $('#threeAdEdit').val('')
                    this.editAdvertise.emit()
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    public openEditModal() {
        this.selectImageGridModal.openEditModal();
    }

    uploadFile(thisItem) {
        let that = this;
        if (thisItem == undefined) {
            this.app.toastWarning("请上传或选择图片");
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.uploadPic = {
                    imageName: thisItem.some.name,
                    imageUrl: tempRes.data.url[0],
                    extension: thisItem.some.type.split('/')[thisItem.some.type.split('/').length - 1],
                    imageSize: thisItem.some.size + 'B',
                    resolution: thisItem.resolution
                }
                that.app.toastSuccess('上传成功');
                that._masterService
                    .postData(that.getImgId, that.uploadPic)
                    .subscribe((res) => {
                        if (res.statusCode == 200) {
                            that._saveVar.threeAdEditPicId = res.data;
                            that.uploader.queue = [];
                        } else {
                            that.app.toastError('错误信息：' + res.errorMessage);
                        }
                    })
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('错误信息：' + response.errorMessage);
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('错误信息：' + response.errorMessage);
        };
        thisItem.upload(); // 开始上传
    }

    selectedFileOnChanged(event: any) {
        let $this = this;
        let thisItem = $this.uploader.queue[0] = $this.uploader.queue[$this.uploader.queue.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(thisItem.some);
        reader.onload = function (e) {
            thisItem.src = this.result as string;
            var img = new Image();
            img.src = thisItem.src;
            img.onload = function () {
                // 存图片的分辨率
                thisItem.resolution = img.width + '*' + img.height;
            }
        }
        this.cdRef.detectChanges();
    }
}
